package com.app.mingluxing.chat;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.adapter.GroupSettingNumAdapter;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.bean.GroupSettingBean;
import com.app.mingluxing.bean.MessageBean;
import com.app.mingluxing.db.DatabaseManager;
import com.app.mingluxing.mqtt.MqttManager;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.GroupFaceUtils;
import com.app.mingluxing.utils.QiniuUtils;
import com.app.mingluxing.widget.GridViewForScrollView;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import de.greenrobot.event.EventBus;

/**
 * 群聊设置页面
 * Created by Aaron on 16/1/28.
 */
public class GroupSettingActivity extends BaseActivity {

    private GridViewForScrollView gvnums;
    private TextView tv_title;
    private TextView tvgroupname;
    //    private ImageView ivshow;
    private ImageView ivremaind;
    private ImageView iv_left;
    private RelativeLayout rlclear;
    private Button btnexit;
    private RelativeLayout rl_group_name;
    private String topic;
    boolean isAdmin = false;//是否是群主
    private ArrayList<GroupSettingBean.TopicEntity.UserListEntity> userList = new ArrayList<>();
    private Intent mIntent;
    private EditText et_group_name;
    private Dialog renameDiago;
    private String groupImgUrl;//群头像
    private String groupName; //群昵称
    private RelativeLayout rl_exchange_master;
    private GroupSettingNumAdapter adapter;
    private GroupSettingBean.TopicEntity topicEntity;

    private boolean childGroup = false;//是否是孩子的群, 孩子的群无法修改群昵称群头像和群信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_group_setting);

        topic = getIntent().getStringExtra("topic");

        if (CommonUtils.isNull(topic)) {
            finish();
            return;
        }

        //是孩子的群, 孩子的群无法修改群昵称群头像和群信息
        if (topic.startsWith(Constant.START_CHILD)) {
            childGroup = true;
        }

        initWidget();

        loadGroupInfo();

        Set<String> remadinSet = sp.getStringSet(Constant.REMAIND + sp.getString(Constant.USERID, ""), null);

        ivremaind.setSelected(!(remadinSet != null && remadinSet.contains(topic)));

        if (childGroup) {
            btnexit.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0x121 && resultCode == 0x122) {
            //退出群成功
            rl_exchange_master.setVisibility(View.INVISIBLE);
            isAdmin = false;
            adapter.setAdmin(false);

            //把新群主设置到第一个位置
            if (data!=null) {
                exChangePosition(data);
            }

        }

    }

    private void exChangePosition(Intent data) {

        String newMasterNum = data.getStringExtra("newMasterNum");

        for (Iterator<GroupSettingBean.TopicEntity.UserListEntity> it = userList.iterator(); it.hasNext(); ) {
            GroupSettingBean.TopicEntity.UserListEntity next = it.next();
            if (next != null && next.user != null && newMasterNum.equals(next.user.phoneNum)) {

                userList.remove(next);
                userList.add(0, next);
                adapter.notifyDataSetChanged();
                return;
            }
        }
    }

    /**
     * 获取群信息
     */
    private void loadGroupInfo() {

        com.alibaba.fastjson.JSONObject js = new com.alibaba.fastjson.JSONObject();
        js.put("token", sp.getString(Constant.TOKEN, ""));
        js.put("topic", topic);

        HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT_TALK + Constant.GROUPINFO, js.toJSONString(), getClass().getName(),
                new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            GroupSettingBean settingBean = JSONObject.parseObject(str, GroupSettingBean.class);

                            if (settingBean == null)
                                return;

                            if (settingBean.code == Constant.STATUS_SUCCESS) {

                                if (settingBean.topic == null)
                                    return;

                                //设置 群设置内容
                                setGroupInfo(settingBean.topic);

                                //判断是否是群成员
                                setWidget(CommonUtils.isFriendOrGroupNum(sp, GroupSettingActivity.this, topic));

                            } else {
                                showToast(Constant.showErrorMsg(settingBean.code, GroupSettingActivity.this));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);

    }

    /**
     * 设置不是群成员时控件的状态
     *
     * @param isNums
     */
    private void setWidget(boolean isNums) {

        if (!isNums) {
            adapter.setChildGroup(true);
            adapter.notifyDataSetChanged();
            tvgroupname.setOnClickListener(null);
            btnexit.setVisibility(View.INVISIBLE);
        }

    }

    /**
     * 设置群设置内容
     *
     * @param topic
     */
    private void setGroupInfo(final GroupSettingBean.TopicEntity topic) {

        this.topicEntity = topic;

        userList = topic.userList;

        if (userList == null || userList.size() < 1)
            return;

        groupImgUrl = topic.groupImgUrl;//群头像
        int mastId = 0;

        //判断自己是否是群主
        for (int i = 0; i < userList.size(); i++) {

            if (topic.userList.get(i).isAdmin) {

                mastId = i;

                if (topic.userList.get(i).user != null
                        && topic.userList.get(i).user.phoneNum.equals(sp.getString(Constant.MOBILE, ""))) {
                    //说明本人是群主
                    isAdmin = true;

                }

                break;
            }

        }

        GroupSettingBean.TopicEntity.UserListEntity masterEntity = userList.get(mastId);

        userList.remove(masterEntity);
        userList.add(0, masterEntity);

        if (isAdmin && !childGroup) {//是群主,并且不是 孩子(/c/)的群 显示群主管理权转让,否则不显示
            rl_exchange_master.setVisibility(View.VISIBLE);
        } else {
            rl_exchange_master.setVisibility(View.INVISIBLE);
        }

        //设置群列表成员的头像
        adapter = new GroupSettingNumAdapter(this, userList, isAdmin, childGroup);
        gvnums.setAdapter(adapter);

        //群昵称
        groupName = topic.groupName;
        tvgroupname.setText(topic.groupName);
        if (!childGroup) {//正常的群聊,(非孩子群聊)

            gvnums.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    if (userList == null)
                        return;

                    if (position == userList.size()) {  // 添加群成员

                        mIntent = new Intent(GroupSettingActivity.this, ChooseGroupNumsActivity.class);
                        mIntent.putExtra("addNums", topic);
                        mIntent.putExtra("style", Constant.ADD_GROUP_NUMS);
                        mIntent.putExtra("groupName", groupName);
                        startActivity(mIntent);

                    }

                    if (position == userList.size() + 1) {  //删除群成员

                        mIntent = new Intent(GroupSettingActivity.this, ChooseGroupNumsActivity.class);
                        mIntent.putExtra("removeNums", topic);
                        mIntent.putExtra("style", Constant.DELETE_GROUP_NUMS);
                        mIntent.putExtra("groupName", groupName);
                        startActivity(mIntent);
                    }

                }
            });
        }
        rl_exchange_master.setOnClickListener(this);

    }

    private void initWidget() {

        this.btnexit = (Button) findViewById(R.id.btn_exit);
        this.rlclear = (RelativeLayout) findViewById(R.id.rl_clear);
        this.ivremaind = (ImageView) findViewById(R.id.iv_remaind);
//        this.ivshow = (ImageView) findViewById(R.id.iv_show);
        this.iv_left = (ImageView) findViewById(R.id.iv_left);
        this.tvgroupname = (TextView) findViewById(R.id.tv_group_name);
        this.tv_title = (TextView) findViewById(R.id.tv_title);
        this.gvnums = (GridViewForScrollView) findViewById(R.id.gv_nums);
        rl_group_name = (RelativeLayout) findViewById(R.id.rl_group_name);
        rl_exchange_master = (RelativeLayout) findViewById(R.id.rl_exchange_master);

        if (!childGroup) {//正常的群聊,(非孩子群聊)
            rl_group_name.setOnClickListener(this);
        }

        btnexit.setOnClickListener(this);
        iv_left.setOnClickListener(this);
        ivremaind.setOnClickListener(this);
        rlclear.setOnClickListener(this);

        tv_title.setText(getResources().getString(R.string.group_setting));

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left://返回
                finish();
                break;

            case R.id.btn_exit://退出群组

                //先判断是否是群成员
                if (CommonUtils.isFriendOrGroupNum(sp, this, topic))
                    exitGroup();
                else
                    setWidget(false);

                break;

            case R.id.rl_exchange_master://转移群主

                mIntent = new Intent(GroupSettingActivity.this, ExchangeMasterActivity.class);
                mIntent.putExtra("topicEntity", topicEntity);
                startActivityForResult(mIntent, 0x121);

                break;

            case R.id.rl_group_name://修改群名称

                //先判断是否是群成员
                if (CommonUtils.isFriendOrGroupNum(sp, this, topic))
                    modifyGroupName();
                else
                    setWidget(false);

                break;

//            case R.id.iv_show://显示群成员昵称
//
//                break;

            case R.id.iv_remaind://群消息提醒

                if (ivremaind.isSelected())
                    setRemaind(false);
                else
                    setRemaind(true);

                ivremaind.setSelected(!ivremaind.isSelected());

                break;

            case R.id.rl_clear://清空聊天记录

                new AlertDialog.Builder(this).setTitle("提醒").setMessage("清空聊天记录,该操作不可恢复").setNegativeButton("取消", null)
                        .setPositiveButton("清空", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                new DeleteTask().execute();
                            }
                        }).show();

                break;

            case R.id.tv_sure:  //修改群昵称

                if (CommonUtils.isNull(et_group_name.getText().toString().trim())) {
                    showToast("请输入群昵称");
                    return;
                }

                //先判断是否是群成员
                if (CommonUtils.isFriendOrGroupNum(sp, this, topic))
                    modifySetting(et_group_name.getText().toString().trim(), groupImgUrl, true);
                else
                    setWidget(false);

                break;

            case R.id.tv_cancle://取消修改群昵称

                if (renameDiago != null && renameDiago.isShowing())
                    renameDiago.dismiss();

                break;

        }

    }

    /**
     * 新消息是否提醒
     *
     * @param remaind
     */
    private void setRemaind(boolean remaind) {

        SharedPreferences.Editor edit = sp.edit();
        Set<String> remaindSet = sp.getStringSet(Constant.REMAIND + sp.getString(Constant.USERID, ""), new LinkedHashSet<String>());

        if (remaind)
            remaindSet.remove(topic);
        else
            remaindSet.add(topic);

        edit.putStringSet(Constant.REMAIND + sp.getString(Constant.USERID, ""), remaindSet).apply();

    }

    /**
     * 修改群昵称
     */
    private void modifyGroupName() {

        renameDiago = new Dialog(this, R.style.no_title);
        renameDiago.setCancelable(true);
        renameDiago.setCanceledOnTouchOutside(true);
        renameDiago.show();

        renameDiago.setContentView(R.layout.diago_change_groupname);

        et_group_name = (EditText) renameDiago.findViewById(R.id.et_group_name);
        TextView tv_sure = (TextView) renameDiago.findViewById(R.id.tv_sure);
        TextView tv_cancle = (TextView) renameDiago.findViewById(R.id.tv_cancle);

        et_group_name.post(new Runnable() {

            @Override
            public void run() {
                InputMethodManager im = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                im.showSoftInput(et_group_name, 0);
            }
        });

        tv_sure.setOnClickListener(this);
        tv_cancle.setOnClickListener(this);

    }


    /**
     * 删除聊天记录的task
     */
    private class DeleteTask extends AsyncTask<String, String, String> {

        private ProgressDialog show;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            show = ProgressDialog.show(GroupSettingActivity.this, "请稍后", "正在删除聊天记录");
        }

        @Override
        protected String doInBackground(String... params) {

            DatabaseManager.getInstance().deleteHistory(GroupSettingActivity.this, topic, sp.getString(Constant.USERID, ""));
            DatabaseManager.getInstance().clearTopic(GroupSettingActivity.this, new String[]{
                    //db.execSQL("update " + Constant.TOPIC_TABLE + " set sendId=?,content=?" +
//                    ",messageType=?,chatType=?,sendTime=?,receivePic=?, receiveName=?,receiveId=? where topic=? and userId=?", args);
                    sp.getString(Constant.USERID, ""), "", Constant.MQTTMESSAGETEXT, "",
                    groupImgUrl, groupName, null, topic, sp.getString(Constant.USERID, "")

            });

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if (show != null && show.isShowing())
                show.dismiss();

            MessageBean mb = new MessageBean();
            mb.operationStyle = Constant.DELETE_RECENT_HISTORY;
            mb.channelId = topic;
            mb.messageType = Constant.MQTTMESSAGETEXT;
//            mb.chatType = Constant.CHAT_GROUP;
            mb.content = "";
            mb.receiveName = groupName;
            mb.receivePic = groupImgUrl;
            EventBus.getDefault().post(mb);//通知 聊天页面 和 最近聊天列表页面 删除聊天记录

            showToast("删除成功");

        }

    }

    /**
     * 退出群
     */
    private void exitGroup() {

        if (isAdmin) {//如果是群主
            showToast("您是群主,请先移交群");
            return;
        }

        //用户编辑过,给出提示
        new AlertDialog.Builder(this).setMessage("退出后不会再接收此群聊消息").setNegativeButton("取消", null).setPositiveButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                if (isAdmin && userList != null && userList.size() > 1) {//如果是群主 并且群成员大于1人时
                    showToast("您是群主,请先移交群");
                    return;
                }

                //调用退出群接口
                com.alibaba.fastjson.JSONObject j = new com.alibaba.fastjson.JSONObject();
                j.put("token", sp.getString(Constant.TOKEN, ""));
                j.put("topic", topic);

                HttpUtil.setPostRequest("退出中...", GroupSettingActivity.this, Constant.WEB_ROOT_TALK + Constant.LEFTGROUP,
                        j.toString(), getClass().getName(), new HttpUtil.SuccessListener() {
                            @Override
                            public void setOnSuccessListener(String str) {

                                try {

                                    org.json.JSONObject j = new org.json.JSONObject(str);
//                                    int code = j.getInt("code");

                                    if (j.getInt("code") == Constant.STATUS_SUCCESS) {

                                        //删除聊天列表中的该topic的聊天条目, 数据库中删除该聊天群的信息, 取消订阅该topic的消息
                                        new ExitTask().execute();

                                    } else {
                                        showToast(Constant.showErrorMsg(j.getInt("code"), GroupSettingActivity.this));
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        }, null);
            }
        }).show();

    }

    /**
     * 退出群的task,删除聊天记录,更改群头像和昵称
     */
    private class ExitTask extends AsyncTask<String, Integer, Bitmap> {
        ProgressDialog clearShow;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            clearShow = ProgressDialog.show(GroupSettingActivity.this, "请稍候", "正在删除聊天记录");

        }

        @Override
        protected Bitmap doInBackground(String... params) {

            Bitmap groupBitmap = null;

            //通知 messageFragment 页面发生改变
            MessageBean mb = new MessageBean();
            mb.operationStyle = Constant.OFF_GROUP;
            mb.channelId = topic;
            EventBus.getDefault().post(mb);

//            //取消订阅该主题
            MqttManager.getInstance().unSubTopic(topic);

            //删除聊天记录
            DatabaseManager.getInstance().deleteHistory(GroupSettingActivity.this ,topic, sp.getString(Constant.USERID, ""));
            //删除topic表中的数据
            DatabaseManager.getInstance().deleteTopic(GroupSettingActivity.this, topic, sp.getString(Constant.USERID, ""));

            //发送群广播,通知修改群头像和昵称

            if (userList == null || userList.size() <= 1) {//如果群里就剩自己一个人 则不需要通知别人
                clearShow.dismiss();
                return null;
            }

            //群昵称 (判断群昵称是否修改过, 修改过则不改了, 没有修改过就删除自己的昵称)
            if (userList != null && userList.size() > 0) {

                boolean change = false;//群昵称是否修改过

                for (int i = 0; i < userList.size(); i++) {

                    String nickName = userList.get(i).user.nickName;

                    if (!groupName.contains(nickName)) {//不包含, 说明修改了群名片
                        change = true;
                        break;
                    }

                }

                List<String> urlImags = new ArrayList<>();
                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < userList.size(); i++) {

                    if (!sp.getString(Constant.USERID, "").equals(userList.get(i).user.phoneNum)) {

                        urlImags.add(userList.get(i).user.imgUrl);//添加头像url
                        if (!change)
                            sb.append(userList.get(i).user.nickName + "、");//群昵称

                    }

                }

                if (!change && sb.length() > 0) {
                    groupName = sb.substring(0, sb.length() - 1);
                }

                //制作群聊新头像
//                return NinePic.getInstance().getSinglePic(GroupSettingActivity.this, urlImags);
                return GroupFaceUtils.createGroupFace(GroupSettingActivity.this, urlImags);
            }

            return groupBitmap;
        }

        @Override
        protected void onPostExecute(Bitmap b) {
            super.onPostExecute(b);

            if (userList == null || userList.size() <= 1) {//如果群里就剩自己一个人 则不需要通知别人
                clearShow.dismiss();
                finish();
                return;
            }

            //请求七牛获取到群头像
            QiniuUtils.getQiniuPic(CommonUtils.compressByte(b), getApplication(), sp.getString(Constant.TOKEN, ""), new QiniuUtils.QiniuSuccessListener() {
                @Override
                public void setOnSuccessListener(String str) {

                    if (clearShow != null && clearShow.isShowing())
                        clearShow.dismiss();

                    sendNotice(str);
                    showToast("退出成功!");
                    finish();
                }
            });

        }
    }

    /**
     * 发送群notice 通知其他人修改群头像和昵称
     *
     * @param groupUrl 群头像
     */
    private void sendNotice(String groupUrl) {

        MessageBean mb = new MessageBean();
        mb.messageType = Constant.MQTTMESSAGENOTICE;
        mb.sendId = sp.getString(Constant.USERID, "");
        mb.sendName = sp.getString(Constant.NICKNAME, "");
        mb.sendPic = sp.getString(Constant.USERIMG, "");
        mb.receiveName = groupName;
        mb.receivePic = groupUrl;
        mb.content = sp.getString(Constant.NICKNAME, "") + "退出了群聊";
        mb.sendDate = System.currentTimeMillis();
        mb.channelId = topic;
//        mb.chatType = Constant.CHAT_GROUP;//群聊
        mb.operationStyle = Constant.OFF_GROUP;

        try {
            MqttManager.getInstance().setMessage(topic, mb);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //调用groupsetting 接口 修改 群昵称和群头像
        modifySetting(mb.receiveName, mb.receivePic, false);

    }

    /**
     * 修改群信息
     * @param isWaring  是否通知其他成员群信息发生了变化,(如果是自己退出群则不要通知其他成员 因为已经有xx退出群的通知了)
     */
    private void modifySetting(final String groupName, final String groupImgUrl, final boolean isWaring) {

        JSONObject js = new JSONObject();
        js.put("token", sp.getString(Constant.TOKEN, ""));
        js.put("topic", topic);
        js.put("groupName", groupName);
        js.put("groupImgUrl", groupImgUrl);

        HttpUtil.setPostRequest("更新中...", this, Constant.WEB_ROOT_TALK + Constant.GROUPSETTING, js.toJSONString(), getClass().getName(),

                new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        if (!isWaring)
                            return;

                        try {

                            org.json.JSONObject j = new org.json.JSONObject(str);

                            if (Constant.STATUS_SUCCESS == j.getInt("code")) {

                                showToast("修改成功");

                                if (renameDiago != null && renameDiago.isShowing())
                                    renameDiago.dismiss();

                                tvgroupname.setText(groupName);

                                MessageBean mb = new MessageBean();
                                mb.messageType = Constant.MQTTMESSAGENOTICE;
                                mb.sendId = sp.getString(Constant.USERID, "");
                                mb.sendPic = sp.getString(Constant.USERIMG, "");
                                mb.sendName = sp.getString(Constant.NICKNAME, "");
                                mb.content = sp.getString(Constant.NICKNAME, "") + " 修改群昵称为 " + groupName;
                                mb.channelId = topic;
                                mb.receivePic = groupImgUrl;
                                mb.receiveName = groupName;
//                                mb.chatType = Constant.CHAT_GROUP;
                                mb.sendDate = System.currentTimeMillis();
                                MqttManager.getInstance().setMessage(topic, mb);

                            } else {
                                showToast(Constant.showErrorMsg(j.getInt("code"), GroupSettingActivity.this));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);

    }

}